import functools

from flask import current_app, abort, session, g

from info.utils.models import User

import  qiniu

def func_index_convert(value):
    index_dict = {1: "first", 2: "second", 3: "third"}
    return index_dict.get(value, "")


def user_login_data(f):

    @functools.wraps(f)
    def wrappers(*args,**kwargs):
        user_id = session.get("user_id")
        user = None
        if user_id:

            try:
                user = User.query.get(user_id)
            except BaseException as e:
                current_app.logger.error(e)
                return abort(500)
        g.user = user

        return f(*args,**kwargs)

    return wrappers

def upload_file(data):
    access_key = "KBHXbVXDH8GTvNLAhSVQIxpk49-s5cXZmlLL5aJu"  # 秘钥
    secret_key = "AGRb047cr1FxTxH82Xe-pdsM3JwFvPZQv__aSGwP"
    bucket_name = "info-news"  # 空间名称

    q = qiniu.Auth(access_key, secret_key)
    key = None
    token = q.upload_token(bucket_name)
    ret, info = qiniu.put_data(token, key, data)
    if ret is not None:  # 上传成功, 返回文件名
        file_name = ret.get("key")
        return file_name
    else:
        raise BaseException(info)